package example1_loginLog.controller;

import example1_loginLog.service.LoginLogService;
import example1_loginLog.vo.User;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "LoginLogServlet", value = "/loginLog")
public class LoginLogServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        LoginLogService logService = new LoginLogService();

        //获取session对象
        HttpSession session = request.getSession();

        //从session中获取登录的用户信息
        User user = (User) session.getAttribute("user");

        if(user!=null){
            //如果session中有已登录用户的信息，直接转发到信息页面，无需重新登录
            request.getRequestDispatcher("/jsp/loginInfo.jsp").forward(request,response);
        }else{
            //如果session中没有已登录用户的信息，需要从页面重新获取用户名和密码重新登录
            String username = request.getParameter("username");
            String password = request.getParameter("password");

            //判断当前用户名和密码是否正确，返回一个用户信息
            User loginUser = logService.login(username,password);

            //正常登录成功
            if(null!=loginUser){
                //把刚刚登录成功的用户放在session中
                session.setAttribute("user",loginUser);

                request.getRequestDispatcher("/jsp/loginInfo.jsp").forward(request,response);
            }else{
                //登录失败
                request.setAttribute("info","登录失败");
                request.getRequestDispatcher("/jsp/loginInfo.jsp").forward(request,response);
            }

        }

    }
}
